package com.zdd.chap5b.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zdd.chap5b.entity.Book;
import com.zdd.chap5b.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class BookController {
    @Autowired
    IBookService bookService;

    @GetMapping("/books")
    public ModelAndView findAllBooks() {
        ModelAndView mv = new ModelAndView();
        List<Book> books = bookService.list();
        mv.addObject("books", books);
        mv.setViewName("index");
        return mv;
    }

    //动态查询书籍
    @GetMapping("/searchBooks")
    public ModelAndView searchBooks(Book book){
        List<Book> books=bookService.searchBooks(book);
        ModelAndView mv=new ModelAndView();
        mv.addObject("books",books);
        mv.setViewName("index");
        return mv;
    }

    @GetMapping("/booksPage")
    public ModelAndView booksPage(@RequestParam(value ="pageNum",defaultValue = "1")int pageNum,@RequestParam(value = "size",defaultValue = "3")int size){
        IPage<Book> page=bookService.getPage(pageNum, size);
        ModelAndView mv=new ModelAndView();
        mv.addObject("page",page);
        mv.setViewName("booksPage");
        return mv;
    }

    @GetMapping("/books2")
    public ModelAndView findAllBooks2(){
        List<Book> books=bookService.list();
        ModelAndView mv=new ModelAndView();
        mv.addObject("books",books);
        mv.setViewName("index");
        return mv;
    }

    @GetMapping("/searchBooks2/{id}")
    public ModelAndView findBooksById2(@PathVariable int id){
        Book book=bookService.getById(id);
        ModelAndView mv=new ModelAndView();
        mv.addObject("book",book);
        mv.setViewName("book");
        return mv;
    }
}
